package com.kgd.news.controller.admin;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.upload.UploadFile;
import com.kgd.news.entity.Image;
import com.kgd.news.utils.BaseController;
import com.kgd.news.utils.DateUtils;
import com.kgd.news.utils.StringUtilsWx;

/**
 * @Email: huangsanm@foxmail.com
 * @Date: 2017/10/10
 * @Time: 下午3:14
 */
public class VideoController extends BaseController {

    /**
     * 搜索的时候会调用这个方法，
     * 点击下一页的时候也调用以下这个方法就可以了吧
     */
    @Override
    public void list() {
        String title = getPara("title");
        String categoryid = getPara("categoryid");
        String sql = "from image where type = 2 ";
        String querytype = "video";
        if (!StringUtilsWx.isEmpty(title)) {
            sql += " and title like '%" + title + "%'";
            querytype += title;
        }
        if (!StringUtilsWx.isEmpty(categoryid)) {
            if ("-1".equals(categoryid)) {
                sql += " and categoryid is null" ;
            } else {
                sql += " and categoryid =" + categoryid;
            }
            querytype += categoryid;
        }
        sql += " order by id desc";
        Page<Image> data = Image.dao.paginate(getPageIndex(querytype), PAGE_SIZE, "select *", sql);
        setAttr("data", data);
        setAttr("categoryid", categoryid);

        render("video_list.html");
    }

    @Override
    public void edit() {
        Integer id = getParaToInt("id");
        Image img = Image.dao.findById(id);
        setAttr("categoryid", getPara("categoryid"));
        setAttr("video", img);
        render("video_edit.html");
    }

    @Override
    public void save() {
        UploadFile uploadFile = getFile("img");
        String filePath = "";
        if (uploadFile != null && !StringUtilsWx.isEmpty(uploadFile.getFileName())) {
            filePath = getFileUploadPath(uploadFile);
        }
        Image us = getModel(Image.class, "video");
        if (!StringUtilsWx.isEmpty(filePath)) {
            us.setCover(filePath);
        }
        String url=  us.getUrl();
        if (url!=null&&url.endsWith("html")) {
            us.setRealurl(url);
        }
        if (us != null && us.getId() != null) {
            us.update();
        } else {
            us.setCreatetime(DateUtils.getCurDateStr());
            us.save();
        }
        CacheKit.removeAll("video");
        CacheKit.removeAll("imageAndVideo");

        list();
    }

    @Override
    public void del() {
        String ids = getPara("ids");
        Db.update("delete from image where id in (" + ids + ")");
        setAttr("categoryid", getPara("categoryid"));
        CacheKit.removeAll("video");
        list();
    }

}
